package com.lanhe.member.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lanhe.common.constant.Constants;
import com.lanhe.common.constant.HttpStatus;
import com.lanhe.common.constant.UserConstants;
import com.lanhe.common.core.domain.entity.LhMemberBase;
import com.lanhe.common.core.domain.entity.dto.MemberMoneyStatisticsDto;
import com.lanhe.common.core.domain.entity.vo.LhMemberStatisticsVo;
import com.lanhe.common.exception.ServiceException;
import com.lanhe.common.utils.DateUtils;
import com.lanhe.common.utils.uuid.IdUtils;
import com.lanhe.member.domain.*;
import com.lanhe.member.domain.dto.BindingMemberBaseDTO;
import com.lanhe.member.domain.dto.LhMemberBaseDTO;
import com.lanhe.member.domain.dto.LhMemberConsumedStatDTO;
import com.lanhe.member.domain.vo.LhMemberBaseVO;
import com.lanhe.member.mapper.LhMemberBaseMapper;
import com.lanhe.member.service.*;
import com.lanhe.order.domain.LhOrdersPool;
import com.lanhe.product.domain.LhLevelInfo;
import com.lanhe.product.service.ILhLevelInfoService;
import com.lanhe.teacher.domain.LhTeacher;
import com.lanhe.teacher.domain.vo.SelectTeacherVo;
import com.lanhe.teacher.service.ILhTeacherService;
import com.lanhe.verifyRec.service.ILhVerifyRecService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.ZoneId;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 会员基础表(LhMemberBase)表服务实现类
 *
 * @author zhanggl
 * @since 2023-12-04 17:01:14
 */
@Service
@Slf4j
public class LhMemberBaseServiceImpl extends ServiceImpl<LhMemberBaseMapper, LhMemberBase> implements ILhMemberBaseService {
	@Resource
	private LhMemberBaseMapper lhMemberBaseMapper;

	@Resource
	private ILhVerifyRecService lhVerifyRecService;//验证码

	@Resource
	private ILhStatYearIncomeService yearIncomeService;

	@Resource
	private ILhStatMonthlyIncomeService monthlyIncomeService;

	@Resource
	private ILhStatWeeklyIncomeService weeklyIncomeService;

	@Resource
	private ILhStatDailyIncomeService dailyIncomeService;

	@Resource
	private ILhMemberRevenueRecService memberRevenueRecordsService;

	@Resource
	private ILhTeacherService teacherService;

	@Resource
	private ILhLevelInfoService lhLevelInfoService;

	@Resource
	private ILhMemberConsumedRecService lhMemberConsumedRecService;

	@Resource
	private ILhMemberRevenueRecService lhMemberRevenueRecService;


	/**
	 * @Description 添加会员基础
	 * @MethodName addLhMemberBase
	 * @Param [dto]
	 * @ReturnType java.lang.Integer
	 * @Date 2023/12/4 17:22
	 * @Author zxx
	 * @Since 1.0
	 */
	@Override
	public LhMemberBase addLhMemberBase(LhMemberBase dto) throws Exception {
		log.info("LhMemberBaseServiceImpl--->addLhMemberBase 添加会员基础信息传参：【{}】", JSON.toJSONString(dto));

		Random random = new Random();
		int min = 10000000; // Minimum 8-digit number
		int max = 99999999; // Maximum 8-digit number

		BigDecimal amount = new BigDecimal("0.00");
		dto.setTotalAmount(amount);
		dto.setBalance(amount);
		dto.setLeaderLevel(0);
		dto.setRegisterChannel(0);
		dto.setRegisterNo(random.nextInt(max - min + 1) + min);
		dto.setUserKey(IdUtils.fastSimpleUUID());//用户唯一key
		dto.setRecentLoginTime(DateUtils.getNowDate());//最后登录时间
		dto.setStatus(UserConstants.NORMAL);
		dto.setDelFlag(UserConstants.NORMAL);
		dto.setCreateTime(DateUtils.getNowDate());
		dto.setUpdateTime(DateUtils.getNowDate());
		lhMemberBaseMapper.insert(dto);

		LhMemberBase memberBase = getLhMemberBaseByWxId(dto.getWxId());
		dto.setMemberId(memberBase.getMemberId());
		log.info("LhMemberBaseServiceImpl--->addLhMemberBase 添加会员基础信息返回结果：【{}】", JSON.toJSONString(dto));
		return dto;
	}

	/**
	 * @Description 更新会员基础
	 * @MethodName updateLhMemberBase
	 * @Param [dto]
	 * @ReturnType java.lang.Integer
	 * @Date 2023/12/4 17:23
	 * @Author zxx
	 * @Since 1.0
	 */
	@Override
	public LhMemberBase updateLhMemberBase(LhMemberBase dto) throws Exception {
		log.info("LhMemberBaseServiceImpl--->updateLhMemberBase 更新会员基础传参：【{}】", JSON.toJSONString(dto));

		LambdaUpdateWrapper<LhMemberBase> updateWrapper = new LambdaUpdateWrapper<>();
		updateWrapper.eq(LhMemberBase::getMemberId, dto.getMemberId());
		int num = lhMemberBaseMapper.update(dto, updateWrapper);
		log.info("LhMemberBaseServiceImpl--->updateLhMemberBase 更新会员基础返回结果：【{}】", JSON.toJSONString(num));
		return dto;
	}

	/**
	 * @Description 会员基础详情
	 * @MethodName getLhMemberBaseDetail
	 * @Param [memberId]
	 * @ReturnType com.lanhe.member.domain.vo.LhMemberBaseVO
	 * @Date 2023/12/4 17:23
	 * @Author zxx
	 * @Since 1.0
	 */
	@Override
	public LhMemberBaseVO getLhMemberBaseDetail(Long memberId) {
		log.info("LhMemberBaseServiceImpl--->getLhMemberBaseDetail 会员基础详情传参：【{}】", JSON.toJSONString(memberId));
		LambdaQueryWrapper<LhMemberBase> queryWrapper = new LambdaQueryWrapper<>();
		queryWrapper.eq(LhMemberBase::getMemberId, memberId);
		LhMemberBase lhMemberBase = lhMemberBaseMapper.selectOne(queryWrapper);
		if (Objects.isNull(lhMemberBase)) {
			throw new ServiceException("用户信息获取失败", HttpStatus.ERROR);
		}
		LhMemberBaseVO lhMemberBaseVO = new LhMemberBaseVO();
		BeanUtils.copyProperties(lhMemberBase, lhMemberBaseVO);

		// 查询老师信息
		if (ObjectUtil.isNotNull(lhMemberBaseVO.getTeacherId())) {
			LhTeacher lhTeacher = teacherService.selectTeacherById(lhMemberBaseVO.getTeacherId());
			if (ObjectUtil.isNotNull(lhTeacher)) {
				lhMemberBaseVO.setTeacherQrCode(lhTeacher.getQrCode());
				lhMemberBaseVO.setTeacherName(lhTeacher.getTeacherName());
			}
		}

		// 查询上级信息
		if (ObjectUtil.isNotNull(lhMemberBaseVO.getRecemMemberId())) {
			LambdaQueryWrapper<LhMemberBase> wrapper = new LambdaQueryWrapper<>();
			wrapper.eq(LhMemberBase::getMemberId, lhMemberBaseVO.getRecemMemberId());
			LhMemberBase recemMember = lhMemberBaseMapper.selectOne(wrapper);
			if (ObjectUtil.isNotNull(recemMember)) {
				lhMemberBaseVO.setRecemName(recemMember.getUserName());
			}
		}

		// 查询vip信息
		if (ObjectUtil.isNotNull(lhMemberBaseVO.getLeaderLevel())) {
			LhLevelInfo lhLevelInfo = lhLevelInfoService.selectLevelInfoByLeaderLevel(lhMemberBaseVO.getLeaderLevel());
			if (ObjectUtil.isNotNull(lhLevelInfo)) {
				lhMemberBaseVO.setLevelId(lhLevelInfo.getLevelId());
			}
		}

		log.info("LhMemberBaseServiceImpl--->getLhMemberBaseDetail 会员基础详情返回结果：【{}】", JSON.toJSONString(lhMemberBaseVO));
		return lhMemberBaseVO;
	}

	/**
	 * @Description 根据微信唯一id 查询账户信息
	 * @MethodName getLhMemberBaseByWxId
	 * @Param [wxId]
	 * @ReturnType com.lanhe.member.domain.LhMemberBase
	 * @Date 2023/12/4 17:41
	 * @Author zxx
	 * @Since 1.0
	 */
	@Override
	public LhMemberBase getLhMemberBaseByWxId(String wxId) throws Exception {
		log.info("LhMemberBaseServiceImpl--->getLhMemberBaseByWxId 根据微信唯一id 查询账户信息传参：【{}】", JSON.toJSONString(wxId));
		LambdaQueryWrapper<LhMemberBase> queryWrapper = new LambdaQueryWrapper<>();
		queryWrapper.eq(LhMemberBase::getStatus, UserConstants.NORMAL);
		queryWrapper.eq(LhMemberBase::getDelFlag, UserConstants.NORMAL);
		queryWrapper.eq(LhMemberBase::getWxId, wxId);
		LhMemberBase lhMemberBase = this.getOne(queryWrapper);
		log.info("LhMemberBaseServiceImpl--->getLhMemberBaseByWxId 根据微信唯一id 查询账户信息返回结果：【{}】", JSON.toJSONString(lhMemberBase));
		return lhMemberBase;
	}

	@Override
	public LhMemberBase getUserByUserKey(String userKey) {

		log.info("LhMemberBaseServiceImpl--->getUserByUserKey 根据userKey 查询账户信息传参：【{}】", JSON.toJSONString(userKey));
		LambdaQueryWrapper<LhMemberBase> queryWrapper = new LambdaQueryWrapper<>();
		queryWrapper.eq(LhMemberBase::getUserKey, userKey);
		queryWrapper.eq(LhMemberBase::getStatus, UserConstants.NORMAL);
		queryWrapper.eq(LhMemberBase::getDelFlag, UserConstants.NORMAL);
		LhMemberBase lhMemberBase = this.getOne(queryWrapper);
		log.info("LhMemberBaseServiceImpl--->getLhMemberBaseByWxId 根据userKey 查询账户信息返回结果：【{}】", JSON.toJSONString(lhMemberBase));
		return lhMemberBase;
	}

	public LhMemberBase getUserByMobile(String mobile) {

		log.info("LhMemberBaseServiceImpl--->getUserByMobile mobile 查询账户信息传参：【{}】", JSON.toJSONString(mobile));
		LambdaQueryWrapper<LhMemberBase> queryWrapper = new LambdaQueryWrapper<>();
		queryWrapper.eq(LhMemberBase::getMobile, mobile);
		queryWrapper.eq(LhMemberBase::getStatus, UserConstants.NORMAL);
		queryWrapper.eq(LhMemberBase::getDelFlag, UserConstants.NORMAL);
		LhMemberBase lhMemberBase = this.getOne(queryWrapper);
		log.info("LhMemberBaseServiceImpl--->getUserByMobile 根据mobile 查询账户信息返回结果：【{}】", JSON.toJSONString(lhMemberBase));
		return lhMemberBase;
	}

	@Override
	public Integer bindMobile(LhMemberBaseDTO dto) {
		log.info("LhMemberBaseServiceImpl--->bindMobile 绑定用户信息：【{}】", JSON.toJSONString(dto));

		// 验证验证码是否正确
		Boolean validate = lhVerifyRecService.validate(dto.getMobile(), dto.getSmsCode(), Constants.GeneralIntType.ONE);
		if (!validate) {
			throw new ServiceException("验证码不正确，请核对。", HttpStatus.ERROR);
		}

		LhMemberBase userByMobile = getUserByMobile(dto.getMobile());
		if (ObjectUtil.isNotEmpty(userByMobile) && !userByMobile.getMemberId().equals(dto.getMemberId())) {
			throw new ServiceException("此手机号已绑定其它账户，请勿重复绑定", HttpStatus.ERROR);
		}

		LhMemberBaseVO lhMemberBaseDetail = getLhMemberBaseDetail(dto.getMemberId());
		if (StringUtils.isNotBlank(lhMemberBaseDetail.getMobile())) {
			throw new ServiceException("您已绑定过手机号，请勿重复绑定", HttpStatus.ERROR);
		}

		LambdaUpdateWrapper<LhMemberBase> updateWrapper = new LambdaUpdateWrapper<>();
		updateWrapper.eq(LhMemberBase::getMemberId, dto.getMemberId());

		LhMemberBase lhMemberBase = new LhMemberBase();
		BeanUtil.copyProperties(dto, lhMemberBase);

		// 查询绑定信息
		if (StringUtils.isNotBlank(dto.getRecemCode())) {
			LhMemberBase memberBase = selectByRegisterNo(dto.getRecemCode());
			if (ObjectUtil.isNotNull(memberBase)) {
				lhMemberBase.setRecemMemberId(memberBase.getMemberId());
				lhMemberBase.setRecemCode(dto.getRecemCode());
			} else {
				throw new ServiceException("您输入的邀请码未查到来源,请核对信息", HttpStatus.ERROR);
			}
		}

		lhMemberBase.setUpdateTime(new Date());
		int num = lhMemberBaseMapper.update(lhMemberBase, updateWrapper);
		log.info("LhMemberBaseServiceImpl--->bindMobile 绑定用户信息：【{}】", JSON.toJSONString(num));

		return num;
	}

	public LhMemberBase selectByRegisterNo(String recemCode) {
		LambdaUpdateWrapper<LhMemberBase> lambdaUpdateWrapper = new LambdaUpdateWrapper<>();
		lambdaUpdateWrapper.eq(LhMemberBase::getRegisterNo, recemCode);
		lambdaUpdateWrapper.eq(LhMemberBase::getStatus, "0");
		lambdaUpdateWrapper.eq(LhMemberBase::getDelFlag, "0");
		return lhMemberBaseMapper.selectOne(lambdaUpdateWrapper);
	}

	@Override
	public List<Object> rankingList(Integer type, Integer pageNum, Integer pageSize) {

		List<Object> objects = new ArrayList<>();

		// 年统计
		if (Constants.GeneralIntType.ONE.equals(type)) {
			List<LhStatYearIncome> statYears = yearIncomeService.rankingList(pageNum, pageSize);
			Set<Long> memberIds = statYears.stream().map(LhStatYearIncome::getMemberId).collect(Collectors.toSet());
			List<LhMemberBase> lhMemberBases = selectByMemberIds(memberIds);
			if (ObjectUtil.isNotNull(lhMemberBases)) {
				Map<Long, LhMemberBase> lhMemberBaseMap = lhMemberBases.stream().collect(Collectors.toMap(LhMemberBase::getMemberId, e -> e));
				for (LhStatYearIncome stat : statYears) {
					stat.setHeadPic(ObjectUtil.isNotNull(lhMemberBaseMap) ? lhMemberBaseMap.get(stat.getMemberId()).getHeadPic() : "");
					stat.setUserName(ObjectUtil.isNotNull(lhMemberBaseMap) ? lhMemberBaseMap.get(stat.getMemberId()).getUserName() : "");
					stat.setProvinceName(ObjectUtil.isNotNull(lhMemberBaseMap) ? lhMemberBaseMap.get(stat.getMemberId()).getProvinceName() : "");
				}
			}
			objects = new ArrayList<>(statYears);
		}

		// 月统计
		if (Constants.GeneralIntType.TWO.equals(type)) {
			List<LhStatMonthlyIncome> statMonthly = monthlyIncomeService.rankingList(pageNum, pageSize);
			Set<Long> memberIds = statMonthly.stream().map(LhStatMonthlyIncome::getMemberId).collect(Collectors.toSet());
			List<LhMemberBase> lhMemberBases = selectByMemberIds(memberIds);
			if (ObjectUtil.isNotNull(lhMemberBases)) {
				Map<Long, LhMemberBase> lhMemberBaseMap = lhMemberBases.stream().collect(Collectors.toMap(LhMemberBase::getMemberId, e -> e));
				for (LhStatMonthlyIncome stat : statMonthly) {
					stat.setHeadPic(ObjectUtil.isNotNull(lhMemberBaseMap) ? lhMemberBaseMap.get(stat.getMemberId()).getHeadPic() : "");
					stat.setUserName(ObjectUtil.isNotNull(lhMemberBaseMap) ? lhMemberBaseMap.get(stat.getMemberId()).getUserName() : "");
					stat.setProvinceName(ObjectUtil.isNotNull(lhMemberBaseMap) ? lhMemberBaseMap.get(stat.getMemberId()).getProvinceName() : "");
				}
			}
			objects = new ArrayList<>(statMonthly);
		}

		// 周统计
		if (Constants.GeneralIntType.THREE.equals(type)) {
			List<LhStatWeeklyIncome> statWeekly = weeklyIncomeService.rankingList(pageNum, pageSize);
			Set<Long> memberIds = statWeekly.stream().map(LhStatWeeklyIncome::getMemberId).collect(Collectors.toSet());
			List<LhMemberBase> lhMemberBases = selectByMemberIds(memberIds);
			if (ObjectUtil.isNotNull(lhMemberBases)) {
				Map<Long, LhMemberBase> lhMemberBaseMap = lhMemberBases.stream().collect(Collectors.toMap(LhMemberBase::getMemberId, e -> e));
				for (LhStatWeeklyIncome stat : statWeekly) {
					stat.setHeadPic(ObjectUtil.isNotNull(lhMemberBaseMap) ? lhMemberBaseMap.get(stat.getMemberId()).getHeadPic() : "");
					stat.setUserName(ObjectUtil.isNotNull(lhMemberBaseMap) ? lhMemberBaseMap.get(stat.getMemberId()).getUserName() : "");
					stat.setProvinceName(ObjectUtil.isNotNull(lhMemberBaseMap) ? lhMemberBaseMap.get(stat.getMemberId()).getProvinceName() : "");
				}
			}
			objects = new ArrayList<>(statWeekly);
		}

		// 天统计
		if (Constants.GeneralIntType.FOUR.equals(type)) {
			List<LhStatDailyIncome> statDaily = dailyIncomeService.rankingList(pageNum, pageSize);
			Set<Long> memberIds = statDaily.stream().map(LhStatDailyIncome::getMemberId).collect(Collectors.toSet());
			List<LhMemberBase> lhMemberBases = selectByMemberIds(memberIds);
			if (ObjectUtil.isNotNull(lhMemberBases)) {
				Map<Long, LhMemberBase> lhMemberBaseMap = lhMemberBases.stream().collect(Collectors.toMap(LhMemberBase::getMemberId, e -> e));
				for (LhStatDailyIncome stat : statDaily) {
					stat.setHeadPic(ObjectUtil.isNotNull(lhMemberBaseMap) ? lhMemberBaseMap.get(stat.getMemberId()).getHeadPic() : "");
					stat.setUserName(ObjectUtil.isNotNull(lhMemberBaseMap) ? lhMemberBaseMap.get(stat.getMemberId()).getUserName() : "");
					stat.setProvinceName(ObjectUtil.isNotNull(lhMemberBaseMap) ? lhMemberBaseMap.get(stat.getMemberId()).getProvinceName() : "");
				}
			}
			objects = new ArrayList<>(statDaily);
		}
		// 总榜
		if (Constants.GeneralIntType.FIVE.equals(type)) {

			LambdaUpdateWrapper<LhMemberBase> lambdaUpdateWrapper = new LambdaUpdateWrapper<>();
			lambdaUpdateWrapper.eq(LhMemberBase::getStatus, "0");
			lambdaUpdateWrapper.eq(LhMemberBase::getDelFlag, "0");
			lambdaUpdateWrapper.orderByDesc(LhMemberBase::getTotalAmount);
			List<LhMemberBase> lhMemberBases = lhMemberBaseMapper.selectList(lambdaUpdateWrapper);
			for (LhMemberBase lhMemberBase : lhMemberBases) {
				lhMemberBase.setAmount(lhMemberBase.getTotalAmount());
			}
			objects = new ArrayList<>(lhMemberBases);
		}

		return objects;
	}

	public List<LhMemberBase> selectByMemberIds(Set<Long> memberIds) {
		List<LhMemberBase> lhMemberBases = new ArrayList<>();
		if (ObjectUtil.isNotEmpty(memberIds)) {
			LambdaUpdateWrapper<LhMemberBase> lambdaUpdateWrapper = new LambdaUpdateWrapper<>();
			lambdaUpdateWrapper.in(LhMemberBase::getMemberId, memberIds);
			lambdaUpdateWrapper.eq(LhMemberBase::getStatus, "0");
			lambdaUpdateWrapper.eq(LhMemberBase::getDelFlag, "0");
			lhMemberBases = lhMemberBaseMapper.selectList(lambdaUpdateWrapper);
		}
		return lhMemberBases;
	}


	@Override
	public void updateDuoyouVipNumber(String vipNumber, Long memberId) {

		LambdaQueryWrapper<LhMemberBase> lambdaQueryWrapper = new LambdaQueryWrapper<>();
		lambdaQueryWrapper.eq(LhMemberBase::getMemberId, memberId);
		LhMemberBase memberBase = lhMemberBaseMapper.selectOne(lambdaQueryWrapper);
		if (ObjectUtil.isNotNull(memberBase)) {

			LhMemberBase memberDb = new LhMemberBase();
			memberDb.setDuoyouVipNumber(vipNumber);
			lhMemberBaseMapper.update(memberDb, lambdaQueryWrapper);
		}
	}

	@Override
	public int updateMemberAmount(LhMemberBase dto) {
		LambdaQueryWrapper<LhMemberBase> lambdaQueryWrapper = new LambdaQueryWrapper<>();
		lambdaQueryWrapper.eq(LhMemberBase::getMemberId, dto.getMemberId());
		LhMemberBase memberBase = lhMemberBaseMapper.selectOne(lambdaQueryWrapper);
		if (ObjectUtil.isNotNull(memberBase)) {

			LhMemberBase memberDb = new LhMemberBase();
			memberDb.setTotalAmount(memberBase.getTotalAmount().add(dto.getTotalAmount()));
			memberDb.setBalance(memberBase.getBalance().add(dto.getBalance()));
			return lhMemberBaseMapper.update(memberDb, lambdaQueryWrapper);
		}
		return 1;
	}

	/**
	 * 1、更新用户收益数据
	 * 2、增加用户收益记录
	 * 3、更新统计数据
	 *
	 * @param ordersPool 实体
	 * @return int
	 * @author zhanggl
	 * @date 2023/12/27
	 */
	@Override
	public void updateMemberBenefits(LhOrdersPool ordersPool) {

		log.info("updateMemberBenefits---> 更新用户收益传参：【{}】", JSON.toJSONString(ordersPool));

		// 增加会员金额
		LhMemberBase memberDb = new LhMemberBase();
		memberDb.setMemberId(ordersPool.getMemberId());
		memberDb.setTotalAmount(ordersPool.getAmount());
		memberDb.setBalance(ordersPool.getAmount());
		updateMemberAmount(memberDb);

		// 增加年统计
		LhStatYearIncome statYearIncome = new LhStatYearIncome();
		statYearIncome.setMemberId(ordersPool.getMemberId());
		statYearIncome.setYear(ordersPool.getYear());
		statYearIncome.setAmount(ordersPool.getAmount());
		yearIncomeService.insertStatYearIncome(statYearIncome);

		// 增加月统计
		LhStatMonthlyIncome statMonthlyIncome = new LhStatMonthlyIncome();
		statMonthlyIncome.setMemberId(ordersPool.getMemberId());
		statMonthlyIncome.setYear(ordersPool.getYear());
		statMonthlyIncome.setMonthly(ordersPool.getMonthly());
		statMonthlyIncome.setAmount(ordersPool.getAmount());
		monthlyIncomeService.insertStatMonthlyIncome(statMonthlyIncome);

		// 增加周统计
		LhStatWeeklyIncome statWeeklyIncome = new LhStatWeeklyIncome();
		statWeeklyIncome.setMemberId(ordersPool.getMemberId());
		statWeeklyIncome.setYear(ordersPool.getYear());
		statWeeklyIncome.setMonthly(ordersPool.getMonthly());
		statWeeklyIncome.setWeekly(ordersPool.getWeekly());
		statWeeklyIncome.setAmount(ordersPool.getAmount());
		weeklyIncomeService.insertStatWeeklyIncome(statWeeklyIncome);

		// 增加天统计
		LhStatDailyIncome statDailyIncome = new LhStatDailyIncome();
		statDailyIncome.setMemberId(ordersPool.getMemberId());
		statDailyIncome.setYear(ordersPool.getYear());
		statDailyIncome.setMonthly(ordersPool.getMonthly());
		statDailyIncome.setWeekly(ordersPool.getWeekly());
		statDailyIncome.setDaily(ordersPool.getDaily());
		statDailyIncome.setAmount(ordersPool.getAmount());
		dailyIncomeService.insertStatDailyIncome(statDailyIncome);

		// 更新收益记录
		LhMemberRevenueRec memberRevenueRecords = new LhMemberRevenueRec();
		memberRevenueRecords.setOrderPoolId(ordersPool.getOrderPoolId());
		memberRevenueRecords.setMemberId(ordersPool.getMemberId());
		memberRevenueRecords.setOrigin(ordersPool.getOrigin());
		memberRevenueRecords.setOrderId(ordersPool.getOrderId());
		memberRevenueRecords.setAmount(ordersPool.getAmount());
		memberRevenueRecords.setRevenueType(ordersPool.getRevenueType());
		memberRevenueRecords.setProductName(ordersPool.getProductName());
		memberRevenueRecords.setProductLog(ordersPool.getProductLog());
		memberRevenueRecords.setReason(ordersPool.getReason());
		memberRevenueRecordsService.insertMemberRevenueRecords(memberRevenueRecords);
	}

	/**
	 * 更新续费次数
	 *
	 * @param memberId 会员ID
	 * @return java.lang.Integer
	 * @author zhanggl
	 * @date 2024/1/5
	 */
	@Override
	public Integer updateRenewNumber(Long memberId) {
		LambdaQueryWrapper<LhMemberBase> lambdaQueryWrapper = new LambdaQueryWrapper<>();
		lambdaQueryWrapper.eq(LhMemberBase::getMemberId, memberId);

		LhMemberBase memberDb = new LhMemberBase();
		memberDb.setRenewNumber(Constants.GeneralIntType.ONE);
		return lhMemberBaseMapper.update(memberDb, lambdaQueryWrapper);
	}

	/**
	 * 更新会员等级
	 *
	 * @param memberId 会员ID
	 * @return java.lang.Integer
	 * @author zhanggl
	 * @date 2024/1/5
	 */
	@Override
	public Integer updateLeaderLevel(Long memberId, Integer three) {
		LambdaQueryWrapper<LhMemberBase> lambdaQueryWrapper = new LambdaQueryWrapper<>();
		lambdaQueryWrapper.eq(LhMemberBase::getMemberId, memberId);

		LhMemberBase memberDb = new LhMemberBase();
		memberDb.setLeaderLevel(three);
		return lhMemberBaseMapper.update(memberDb, lambdaQueryWrapper);
	}

	/**
	 * 更新会员基础余额
	 *
	 * @param memberId 用户ID
	 * @param amount   金额
	 * @param type     类型
	 * @author zhanggl
	 * @date 2024/1/5
	 */
	@Override
	public void updateMemberBaseBalance(Long memberId, BigDecimal amount, Integer type) {
		LambdaQueryWrapper<LhMemberBase> lambdaQueryWrapper = new LambdaQueryWrapper<>();
		lambdaQueryWrapper.eq(LhMemberBase::getMemberId, memberId);

		LhMemberBase memberBase = lhMemberBaseMapper.selectById(memberId);
		LhMemberBase memberDb = new LhMemberBase();

		// 如果拒绝，还原余额
		if (type.equals(Constants.ORDERS_WITHDRAWAL_STATUS_3)) {
			memberDb.setBalance(memberBase.getBalance().subtract(amount));
		}
		memberDb.setLockAmount(memberBase.getLockAmount().subtract(amount));
		lhMemberBaseMapper.update(memberDb, lambdaQueryWrapper);
	}

	/**
	 * 更新会员基础余额
	 *
	 * @param memberId 用户ID
	 * @param amount   金额
	 * @author zhanggl
	 * @date 2024/1/5
	 */
	@Override
	public int updateLhMemberBalance(Long memberId, BigDecimal amount) {

		LambdaQueryWrapper<LhMemberBase> lambdaQueryWrapper = new LambdaQueryWrapper<>();
		lambdaQueryWrapper.eq(LhMemberBase::getMemberId, memberId);

		LhMemberBase memberBase = lhMemberBaseMapper.selectById(memberId);
		LhMemberBase memberDb = new LhMemberBase();


		memberDb.setBalance(memberBase.getBalance().subtract(amount));
		if (ObjectUtil.isNull(memberBase.getLockAmount())) {
			memberDb.setLockAmount(amount);
		} else {
			memberDb.setLockAmount(memberBase.getLockAmount().add(amount));
		}

		return lhMemberBaseMapper.update(memberDb, lambdaQueryWrapper);
	}

	/**
	 * 会员基础列表
	 *
	 * @param lhMemberBase
	 * @return
	 */
	@Override
	public List<LhMemberBase> selectLhMemberBaseList(LhMemberBase lhMemberBase) {
//		LambdaQueryWrapper<LhMemberBase> lambdaQueryWrapper = new LambdaQueryWrapper<>();
//		// 用户昵称
//		lambdaQueryWrapper.like(StringUtils.isNotBlank(lhMemberBase.getUserName()), LhMemberBase::getUserName, lhMemberBase.getUserName());
//		// 等级
//		lambdaQueryWrapper.eq(ObjectUtil.isNotNull(lhMemberBase.getLeaderLevel()), LhMemberBase::getLeaderLevel, lhMemberBase.getLeaderLevel());
//		// 手机号码
//		lambdaQueryWrapper.like(StringUtils.isNotBlank(lhMemberBase.getMobile()), LhMemberBase::getMobile, lhMemberBase.getMobile());
//		// 上级归属
//		lambdaQueryWrapper.eq(ObjectUtil.isNotNull(lhMemberBase.getRecemCode()),LhMemberBase::getRecemCode,lhMemberBase.getRecemCode());
//		// 删除标志
//		lambdaQueryWrapper.eq(LhMemberBase::getDelFlag, 0);
//		lambdaQueryWrapper.orderByDesc(LhMemberBase::getCreateTime);

		return lhMemberBaseMapper.selectLhMemberBaseList(lhMemberBase);
	}

	/**
	 * 老师批量绑定学员
	 *
	 * @param bindingMemberBaseDTO
	 * @return
	 */
	@Override
	public int bindingMemberBase(BindingMemberBaseDTO bindingMemberBaseDTO) {
		return lhMemberBaseMapper.bindingMemberBase(bindingMemberBaseDTO);
	}

	/**
	 * 减少积分
	 *
	 * @param memberId   会员ID
	 * @param renewScore 积分
	 * @author zhanggl
	 * @date 2024/1/17
	 */
	@Override
	public int reduceResidueScore(Long memberId, Integer renewScore) {

		LambdaQueryWrapper<LhMemberBase> lambdaQueryWrapper = new LambdaQueryWrapper<>();
		lambdaQueryWrapper.eq(LhMemberBase::getMemberId, memberId);

		LhMemberBase memberBase = lhMemberBaseMapper.selectById(memberId);
		LhMemberBase memberDb = new LhMemberBase();

		memberDb.setResidueScore(memberBase.getResidueScore() - renewScore);
		return lhMemberBaseMapper.update(memberDb, lambdaQueryWrapper);
	}

	/**
	 * 更新用户等级及有效期
	 *
	 * @param memberId     会员ID
	 * @param leaderLevel  等级
	 * @param validityDays 天数
	 * @param orderType    类型
	 * @author zhanggl
	 * @date 2024/1/17
	 */
	@Override
	public int updateMemberLevelAndExpiryDate(Long memberId, Integer leaderLevel, Integer validityDays, Integer orderType) {

		LambdaQueryWrapper<LhMemberBase> lambdaQueryWrapper = new LambdaQueryWrapper<>();
		lambdaQueryWrapper.eq(LhMemberBase::getMemberId, memberId);
		LhMemberBase memberBase = lhMemberBaseMapper.selectById(memberId);

		LhMemberBase memberDb = new LhMemberBase();
		if (Constants.ORDER_TYPE_1.equals(orderType)) {

			// 获取当前日期
			LocalDate currentDate = LocalDate.now();

			// 增加增加天数
			LocalDate newDate = currentDate.plusDays(validityDays);
			SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			Date date = null;
			try {
				date = dateFormat.parse(newDate + " 23:59:59");
			} catch (ParseException e) {
				throw new RuntimeException(e);
			}

			memberDb.setExpiryDate(date); // 更新日期
			memberDb.setRenewNumber(0); // 更新续费次数
			memberDb.setLeaderLevel(leaderLevel); // 更新用户等级

		} else {

			// 续费

			// 获取当前日期
			LocalDate currentDate = LocalDate.now();
			if (memberBase.getExpiryDate() != null) {
				currentDate = memberBase.getExpiryDate().toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
			}

			// 增加增加天数
			LocalDate newDate = currentDate.plusDays(validityDays);
			SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			Date date = null;
			try {
				date = dateFormat.parse(newDate + " 23:59:59");
			} catch (ParseException e) {
				throw new RuntimeException(e);
			}
			memberDb.setExpiryDate(date);
			memberDb.setRenewNumber(memberBase.getRenewNumber() + 1);

		}
		return lhMemberBaseMapper.update(memberDb, lambdaQueryWrapper);
	}

	@Override
	public LhMemberStatisticsVo getMemberStat() {
		// 用户的总额，待提现，已提现， 总注册量
		MemberMoneyStatisticsDto memberMoneyStatisticsDto = lhMemberBaseMapper.selectMemberMoneyStat();
		// 今日用户注册量
		long enrollToday = lhMemberBaseMapper.selectMemberEnrollToday();
		// 本月的用户注册量
		long enrollMonth = lhMemberBaseMapper.selectMemberEnrollMonth();
		/**
		 * 消费和总额
		 */
		// 今日的用户消费次数和总额
		LhMemberConsumedStatDTO consumptionToday = lhMemberConsumedRecService.selectConsumptionToday();
		// 本月的用户消费次数和总额
		LhMemberConsumedStatDTO consumptionMonth = lhMemberConsumedRecService.selectConsumptionMonth();
		// 累计的用户消费次数和总额
		LhMemberConsumedStatDTO consumptionSum = lhMemberConsumedRecService.selectConsumptionSum();
		/**
		 *  用户收益
		 */
		// 今日的用户收益总额
		BigDecimal amountToday = lhMemberRevenueRecService.selectEarningsToday();
		// 本月的用户收益总额
		BigDecimal amountMonth = lhMemberRevenueRecService.selectEarningsMonth();
		// 累计的用户收益总额
		BigDecimal amountSum = lhMemberRevenueRecService.selectEarningsSum();

		LhMemberStatisticsVo statisticsVo = new LhMemberStatisticsVo();
		statisticsVo.setTotalAmount(memberMoneyStatisticsDto.getTotalAmount());
		statisticsVo.setBalance(memberMoneyStatisticsDto.getBalance());
		statisticsVo.setWithdrawnAmount(memberMoneyStatisticsDto.getWithdrawnAmount());
		statisticsVo.setEnrollStat(memberMoneyStatisticsDto.getEnrollStat());
		statisticsVo.setEnrollToday(enrollToday);
		statisticsVo.setEnrollMonth(enrollMonth);
		statisticsVo.setConsumptionTodayCount(consumptionToday.getCount());
		statisticsVo.setConsumptionTodayAmount(consumptionToday.getAmount());
		statisticsVo.setConsumptionMonthCount(consumptionMonth.getCount());
		statisticsVo.setConsumptionMonthAmount(consumptionMonth.getAmount());
		statisticsVo.setConsumptionSumCount(consumptionSum.getCount());
		statisticsVo.setConsumptionSumAmount(consumptionSum.getAmount());
		statisticsVo.setAmountToday(amountToday);
		statisticsVo.setAmountMonth(amountMonth);
		statisticsVo.setAmountSum(amountSum);
		return statisticsVo;
	}
}

